package com.godenwater.recv.server.qx;

import com.godenwater.core.weixin.common.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Li on 2017/4/14.
 */
public class QxMessagePaser {

    public QxMessage parse(String content){
        int pos = 0;
        String[] tokens = content.split(",");
        for(String token:tokens){
            System.out.println(">> " + (pos++) + " "+ token);
        }

        QxMessageHeader header = new QxMessageHeader();
        header.setAreacode(tokens[1]);
        header.setLgtd(tokens[2]);
        header.setLttd(tokens[3]);
        header.setHigh(tokens[4]);
        header.setType(tokens[5]);
        header.setDevtype(tokens[6]);
        header.setDevid(tokens[7]);
        header.setTm(tokens[8]);
        header.setFlag(tokens[9]);
        header.setNitem(tokens[10]);
        header.setNstatus(tokens[11]);


        QxMessage message = new QxMessage();
        message.setHeader(header);

        pos = 12;
       if(StringUtils.isNotBlank( header.getNitem())){
           List<QxMessageItem> items = new ArrayList<QxMessageItem>();
            int n = Integer.parseInt(header.getNitem().trim());
            for(int i=0;i<n;i++){
                QxMessageItem item = new QxMessageItem();
                item.setText(tokens[pos+0]);
                item.setValue(tokens[pos+1]);
                items.add(item);
                pos = pos + 2;
            }
           message.setVitems(items);
       }

        message.setControl(tokens[pos]);//质量控制

        pos = pos + 1;
        if(StringUtils.isNotBlank( header.getNstatus())){
            List<QxMessageItem> items = new ArrayList<QxMessageItem>();
            int n = Integer.parseInt(header.getNstatus().trim());
            for(int i=0;i<n;i++){
                QxMessageItem item = new QxMessageItem();
                item.setText(tokens[pos+0]);
                item.setValue(tokens[pos+1]);
                items.add(item);
                pos = pos + 2;
            }
            message.setVstatus(items);
        }

        message.setMcrc(tokens[pos]);//校验位

        return message;
    }

    public static void main(String[] args){
        QxMessagePaser parser = new QxMessagePaser();
        String msg = "BG,12345, 321420 ,1163418 ,01000,18,YNAI,001, 20120912131000,005,009,03,ASA,010001, AAA5,-102, ADA5,080, ASB,0300, ASC,1000, ASD,-100, ASE,080, ASF,10000, ASG,000200,000000000,z,1,y_AAA,2,wA,4,9574,ED";
        parser.parse(msg);

    }

}
